import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { RetReqApi } from "@/api/erp/purchase/retReq";
import { message, Tabs, Button } from "antd";
import { useTranslation } from "react-i18next";
import { useState, useMemo, useEffect } from "react";
import { handleTree } from "@/utils/tree";
import * as UserApi from "@/api/system/user";
import { listSimpleDept } from "@/api/system/dept";
import { BasicProTable, useProTable } from "@/components/ViewComponents/proTable";
import "./index.less";
import { productApi } from "@/api/erp/drug/drug";
let reload: Function;
let applyId: any;
const index = (props: { register: Fn }) => {
	const [isUpdated, setIsUpdated] = useState(false);
	const { t } = useTranslation();
	const en_vi = "drugStorage.purchasingManagement.other";
	const [treeData, setTreeData] = useState([]);
	const formSchema: FormSchema[] = [
		{
			label: t(`${en_vi}.patId`),
			component: "Input",
			field: "patId"
		},
		{
			label: t(`${en_vi}.deptName`),
			field: "deptId",
			component: "TreeSelect",
			componentProps: {
				treeData,
				fieldNames: {
					value: "id",
					label: "name"
				}
			}
		},
		{
			label: t(`${en_vi}.applyPersonId`),
			component: "ApiSelect",
			field: "applyPersonId",
			componentProps: {
				api: UserApi.getListSimpleUsers,
				labelField: "nickname",
				valueField: "id",
				immediate: false
			}
		},
		{
			label: t(`${en_vi}.applyDate`),
			field: "applyDate",
			component: "DatePicker"
		},
		{
			label: t(`${en_vi}.exportDate`),
			field: "exportDate",
			component: "DatePicker"
		}
	];
	const getTitle = useMemo(() => {
		return isUpdated ? t("felix_ui.edit") : t("felix_ui.add");
	}, [isUpdated]);
	const [formTop, { validateFields, setFieldsValue: setFieldsValueFn, resetFields }] = useForm({
		schemas: formSchema,
		labelWidth: 120,
		baseColProps: {
			span: 12
		}
	});
	const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(props.register, data => {
		reload = data.reload;
		applyId = data.record?.applyId;
		resetFields();
		setDrawerProps({ confirmLoading: true });
		setIsUpdated(!!data?.isUpdated);
		data.isUpdated
			? setFieldsValue(data.record?.refundApplyExlist)
			: setFieldsValue([
					{
						key: new Date().getTime(),
						drugId: undefined,
						qty: undefined,
						purchasePrice: undefined,
						sqNumb: undefined
					}
			  ]);
		setFieldsValueFn({
			...data.record
		});
		setDrawerProps({ confirmLoading: false });
	});
	const dataSource = [
		{
			key: new Date().getTime(),
			drugId: undefined,
			qty: undefined,
			purchasePrice: undefined,
			sqNumb: undefined
		}
	];
	const defaultColumns = [
		{
			title: t("felix_ui.sq_numb"),
			// dataIndex: "sq_numb",
			render: (text, record, index) => index * 1 + 1 // 设置序号
		},
		{
			title: t("drugStorage.productName"),
			type: "ApiSelect",
			dataIndex: "drugId",
			editable: true,
			componentProps: {
				api: productApi.getproductSimpleList,
				labelField: "productName",
				valueField: "productId",
				immediate: false,
				params: {
					bizType: "1"
				}
			},
			width: 200
		},
		{
			title: t(`${en_vi}.sqNumb`),
			dataIndex: "sqNumb",
			editable: true
		},
		{
			title: t(`${en_vi}.qty`),
			dataIndex: "qty",
			editable: true
		},
		{
			title: t(`drugStorage.bid.purchasePrice`),
			dataIndex: "purchasePrice",
			editable: true
		},
		{
			title: t("felix_ui.action"),
			render: (_, obj) => {
				return <Button onClick={onDelete(obj)}>{t("felix_ui.delete")}</Button>;
			}
			// fixed: "right"
		}
	];
	const [proTable, { submit, handleAdd, handleDelete, setFieldsValue }] = useProTable({
		defaultColumns,
		dataSource
	});
	const onAdd = () => {
		handleAdd({
			key: new Date().getTime(),
			drugId: undefined,
			qty: undefined,
			purchasePrice: undefined,
			sqNumb: undefined
		});
	};
	const onDelete = obj => () => {
		handleDelete(obj.key);
	};
	const handleSubmit = async () => {
		const formValue = await validateFields();
		const items = await submit();
		formValue.refundApplyExlist = items;
		formValue.exportDate = new Date(formValue.exportDate).getTime();
		formValue.applyDate = new Date(formValue.applyDate).getTime();
		let res;
		if (isUpdated) {
			formValue.applyId = applyId;
			res = await RetReqApi.updateRetReq(formValue);
		} else {
			res = await RetReqApi.createRetReq(formValue);
		}
		if (!res) {
			message.error(t("viewComponents.patientInformation.additionFailed"));
			return;
		}
		message.success(t("viewComponents.patientInformation.successfullyAdded"));
		closeDrawer();
		reload();
	};
	useEffect(() => {
		const getTreeData = async () => {
			const data = await listSimpleDept();
			let root: any = { id: 0, name: "部门分类", children: [] };
			root.children = handleTree(data, "id", "parentId");
			let newTreeData = treeData;
			newTreeData.push(root);
			setTreeData(newTreeData);
		};
		getTreeData();
	}, []);
	return (
		<BasicDrawer size="large" {...props} title={getTitle} register={registerDrawer} ok={handleSubmit} showFooter={true}>
			<Tabs>
				<Tabs.TabPane tab={t("drugStorage.inventorydrugs")}>
					<BasicForm register={formTop}></BasicForm>
					<Button onClick={onAdd}> {t("felix_ui.add")}</Button>
					<div style={{ width: "100%", overflow: "auto" }}>
						<BasicProTable register={proTable}></BasicProTable>
					</div>
				</Tabs.TabPane>
			</Tabs>
		</BasicDrawer>
	);
};
export default index;
